<?php

class UpgradeUserForm extends CFormModel
{
	public $detail;
	public $account;
	
	public $uid;
	public $first_name;
	public $last_name;
	public $address;
	public $phone;
	
	public $email;
	
	public function rules()
	{
		return array(
			array('first_name, last_name, address, phone, email', 'required'),
			array('email', 'email'),
		);
	}
	
	public function upgrade()
	{
		$transaction = Yii::app()->db->beginTransaction();
		try {
			$this->uid = Yii::app()->user->id;
			$this->account = Account::model()->findByPk($this->uid);
			$this->detail = AccountDetail::model()->findByPk($this->uid);
			if($this->detail == null){
				$this->detail = new AccountDetail();
				$this->detail->uid = $this->uid;
			}
			if(!empty($this->first_name)){ $this->detail->first_name = $this->first_name; }
			if(!empty($this->last_name)){ $this->detail->last_name = $this->last_name; }
			if(!empty($this->address)){ $this->detail->address = $this->address; }
			if(!empty($this->phone)){ $this->detail->phone = $this->phone; }
			
			if(empty($this->account->email)){
				$this->account->email = $this->email;
				if($this->validate(array('email'))){
					throw new Exception('email invalid.');
				}
				if(!empty($this->account->email)){
					throw new Exception('email empty.');
				}
				if(!$this->account->save()){
					throw new Exception('Can not save account.');
				}
			}
			if(!$this->detail->save()){
				throw new Exception('Can not save detail.');
			}
			if(!$this->isUpgradeFull()){
				throw new Exception('Upgrade not full.');
			}
			$verifyEmail = new VerifyEmail();
			$verifyEmail->uid = $this->uid;
			$verifyEmail->verify_code = Helper::genToken();
			if(!$verifyEmail->save()){
				throw new Exception('Can not make verify email code.');
			}
			$transaction->commit();
			return true;
		}
		catch(Exception $e) {
			$transaction->rollback();
			return false;
		}
	}
	
	public function isUpgradeFull()
	{
		if(!empty($this->detail->first_name)
			&& !empty($this->detail->first_name)
			&& !empty($this->detail->first_name)
			&& !empty($this->detail->first_name)
			&& !empty($this->account->email))
		{
			return true;
		}
		return false;
	}
}